<template>
    <div class="container">
        <div class="header">
            <el-button type="primary" size="mini" @click="refreshStatic">刷新</el-button>
            <el-button type="primary" size="mini" @click="queryStatic">查询</el-button>
            <el-button type="primary" size="mini" v-authCode.show="B_0153" @click="loadout">导出</el-button>
        </div>
        <div class="dataInfo">
            <div style="height: calc(100vh - 210px)">
                <vxe-table
                    auto-resize
                    height="100%"
                    border
                    stripe
                    ref="xTable"
                    resizable
                    :data="tableDataResult"
                    @checkbox-all="selectAllValueEvent"
                    @checkbox-change="selectValueChangeEvent"
                    @sort-change="handleSort"
                    :sort-config="{
                        defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                        remote: true,
                    }"
                    highlight-hover-row
                    :key="tableDataResultNumKey + 'tableDataResultNumKey'"
                    v-loading="tableDataResultLoading"
                    header-align="center"
                    show-header-overflow
                    show-overflow
                >
                    <vxe-table-column type="checkbox" min-width="40" fixed="left"></vxe-table-column>
                    <vxe-column
                        v-for="item in showFieldList"
                        :fixed="item.type === 'btn' ? (item.fixed ? item.fixed : 'right') : ''"
                        :key="item.id"
                        :width="item.width || ''"
                        :min-width="item.minWidth || '100'"
                        :title="item.content"
                        :field="item.id"
                        :sortable="!['reportCode', 'reportName', 'marketName'].includes(item.id)"
                        header-align="center"
                        :align="getAlign(item)"
                    >
                        <template #default="{ row }">
                            <span v-if="item.type == 'func'">
                                {{ item.funcBody(row[item.id], row) || '--' }}
                            </span>
                            <span v-else-if="item.type == 'statusTag'">
                                <StatusTag :code="row[item.id]"></StatusTag>
                            </span>
                            <span v-else-if="item.type == 'status'">
                                {{ item.statusKV[row[item.id]] }}
                            </span>
                            <span v-else-if="item.type == 'date'">
                                {{ dateFormat(row[item.id]) || '--' }}
                            </span>

                            <span v-else-if="item.id == 'dictStockCodes'" :key="fieldKey + 'dictStockCodes'">
                                <el-tooltip placement="bottom" popper-class="tips-popper">
                                    <div slot="content" v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length > 1">
                                        <div v-for="(item, index) in row.dictStockCodes" :key="index">
                                            {{ item.dictKey + '(' + item.dictKeyName + ')' }}
                                        </div>
                                    </div>

                                    <el-tag v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length > 1" style="cursor: default">
                                        {{ row.dictStockCodes.length + '个证券' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length === 1">
                                    {{ row.dictStockCodes[0].dictKey + '(' + row.dictStockCodes[0].dictKeyName + ')' }}
                                </span>
                                <span
                                    v-if="
                                        !row.hasOwnProperty('dictStockCodes') ||
                                        (row.hasOwnProperty('dictStockCodes') && row.dictStockCodes.length === 0)
                                    "
                                >
                                    --
                                </span>
                            </span>
                            <span v-else-if="item.id == 'branchValues'" :key="fieldKey + 'branchValues'">
                                <el-tooltip placement="bottom">
                                    <div slot="content" v-if="row.hasOwnProperty('branchValues') && row.branchValues.length > 1">
                                        <div v-for="(item, index) in row.branchValues" :key="index">
                                            {{ item.replace(/(\.|\d+)$/, $1 => numberFormat($1)) }}
                                        </div>
                                    </div>
                                    <el-tag v-if="row.hasOwnProperty('branchValues') && row.branchValues.length > 1" style="cursor: default">
                                        {{ row.branchValues.length + '个分支' }}</el-tag
                                    >
                                </el-tooltip>
                                <span v-if="row.hasOwnProperty('branchValues') && row.branchValues.length === 1">{{
                                    row.branchValues[0].replace(/(\.|\d+)$/, $1 => numberFormat($1))
                                }}</span>
                            </span>
                            <span v-else-if="item.id == 'investBalance'" :key="fieldKey + 'investBalance'">
                                <span v-if="!row.investBalance || !row.investBalance.trim()"></span>
                                <el-popover
                                    v-else-if="getObjectLength(JSON.parse(row.investBalance)) && getObjectLength(JSON.parse(row.investBalance)) > 1"
                                    placement="top"
                                    trigger="hover"
                                >
                                    <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in JSON.parse(row.investBalance)" :key="key">
                                        {{ '阀值' + ++index + '可投余量: ' + JSON.parse(row.investBalance)['INVESTABLE_BALANCE_' + index] }}
                                    </div>
                                    <el-tag slot="reference">{{ getObjectLength(JSON.parse(row.investBalance)) + '个可投余量' }}</el-tag>
                                </el-popover>
                                <span v-else v-for="(value, key) in JSON.parse(row.investBalance)" :key="key">{{ value }}</span>
                            </span>
                            <span v-else>
                                {{ row[item.id] === 0 || (row[item.id] && (row[item.id] + '').trim()) ? row[item.id] : '--' }}
                            </span>
                        </template>
                    </vxe-column>
                    <vxe-table-column title="操作" show-overflow min-width="150" fixed="right" align="center">
                        <template #default="{ row }">
                            <RiskIconButton type="primary" topTitle="详情" icon="el-icon-view" @on-click="handleRowOperateSumLook(row)"></RiskIconButton>
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </div>
            <RiskPagination :paging="page" @page-change="pageQuery"></RiskPagination>
        </div>
        <StaticResultSumSearch
            v-if="staticResultQueryDialogVO.visible"
            :staticResultQueryDialogVO="staticResultQueryDialogVO"
            :reqVO="staticResultReqVO"
            @staticResultQueryReturn="staticResultQueryReturn"
            :editableTabsValue="activeValue"
            :showErrorType="showErrorType"
        >
        </StaticResultSumSearch>

    </div>
</template>
<script lang="ts">
import Dict from '../../../../pages/static/dict';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import StaticResultDetail from '../../../../pages/static/risk-result/static-result-detail.vue';
import StaticResultSumSearch from './static-result-sum-search.vue';
import { numberFormat, unitShow, dateFormat, thousandsFormat, timeFormat, getConfigItem, numberFormatXDAY } from '@/utils/tools';
import ColumnUtil from '@/pages/risk-time/utils/column-util';
import { downLoadFile } from '@/utils/request';
import { getTableLayout } from '@/common/api/commonApi';
import { DialogVO } from '@yhfin/biz';
import { getSystem } from '@/utils/user-util';
import DictionConstUtil from '@/utils/diction-const-util';

@Component({
    name: 'RiskResultSumTab',
    components: {
        RiskIconButton,
        StaticResultSumSearch,
        StaticResultDetail,
        StatusTag,
        BranchTag,
        RiskTableLayout,
        RiskPagination,
    },
})
export default class RiskResultSumTab extends Vue {
    @Prop() activeValue: string;
    @Prop() assetList: any;
    @Prop() fdAcList: any;

    numberFormat = numberFormat;
    unitShow = unitShow;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    WEB_DOCKING = getConfigItem('WEB_DOCKING');

    sortProp: string = 'triggerType';
    sortOrder: string = 'desc'; // 排序方式

    private page: any = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    showErrorType: boolean = false; // 是否展示错误类型
    private tableDataResultLoading: boolean = false; // 静态结果加载

    // 静态结果请求参数
    private staticResultReqVO: any = {
        calculateDateEnd: '',
        calculateDateStart: '',
        entryCodes: '',
        entryGroups: [],
        entryKey: '',
        entryName: '',
        excludeEntryGroup: false,
        fundGroups: [],
        paging: { total: 0, currentPage: 1, totalPage: 0, pageSize: 50 },
        prohibitionDate: '',
        reBankCode: '',
        reFundCode: '',
        reIssueCode: '',
        reStockCode: '',
        resultId: '',
        showNewRecord: '1',
        tradeDateStart: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        tradeDateEnd: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        triggerTypeList: [],
        precision: false,
        sort: '',
        fundTypes: [],
        fdProductCodes: [],
    };

    // 结果查询参数
    sortParamObj = {
        resultId: 'N_RESULT_ID',
        tradeDate: 'D_TRADE_DATE',
        calculateDate: 'D_CAL_DATE',
        dictFundCodes: 'C_FUND_CODES',
        triggerType: 'C_TRIGGER_TYPE',
        entryName: 'C_ENTRY_NAME',
        result: 'N_RESULT',
        prohibitionDate: 'N_PROHIBITION_DATE',
        triggerDay: 'N_TRIGGER_DAY',
        dictStockCodes: 'LENGTH(C_STOCK_CODES)',
        branchValues: 'C_BR_VALUES',
        compareType: 'C_COMPARE_TYPE',
        thresholdValue: 'N_THRESHOLD_VALUE',
        legalDays: 'N_LEGAL_DAYS',
        insideDays: 'N_INSIDE_DAYS',
        frequency: 'N_FREQUENCY',
        resultInformation: 'length(C_OUTCOME_INFORMATION)',
        investBalance: 'C_INVEST_BALANCE',
        assetCodes: 'LENGTH(C_ASSET_CODES)',
        fdAcCodes: 'LENGTH(C_FD_AC_CODES)',
        errorMessage: 'C_ERROR_MESSAGE',
        fdProductCode: 'C_FD_PRODUCT_CODE',
        fundType: 'C_FUND_TYPE',
        numerator: 'N_NUMERATOR',
        denominator: 'N_DENOMINATOR',
    };

    // 历史结果参数
    historyColumns: any = [
        {
            id: 'tradeDate',
            content: '估值日期',
            type: 'date',
            align: 'center',
            minWidth: 120,
        },
        {
            id: 'calculateDate',
            content: '计算日期',
            type: 'func',
            funcBody: (value, row) => dateFormat(row['calculateDate']) + '\n' + timeFormat(row['calculateTime']),
            align: 'center',
            minWidth: 160,
        },
        {
            id: 'dictFundCodes',
            content: '产品代码(名称)',
            minWidth: 160,
            type: 'func',
            funcBody: value => this.formatDictFundCodes(value),
        },
        {
            id: 'triggerType',
            content: '触警类型',
            type: 'statusTag',
        },
        {
            id: 'entryCode',
            content: '条目编号',
        },
        {
            id: 'entryName',
            content: '风险说明',
            minWidth: 120,
        },
        {
            id: 'resultCount',
            content: '结果总数',
            minWidth: 120,
        },
        {
            id: 'alertRate',
            content: '触警率',
            minWidth: 120,
        },
        {
            id: 'compareType',
            content: '条目比较方向',
            type: 'status',
            statusKV: Dict.CompareDirection,
            minWidth: 140,
        },
        {
            id: 'thresholdValue',
            content: '条目触发值',
            type: 'func',
            funcBody: (value, row) => (row.thresholdValue != undefined ? numberFormat(row.thresholdValue, row.unit) + unitShow(row.unit) : '--'),
            minWidth: 120,
        },
    ];

    columns: any[] = [
        {
            id: 'legalDays',
            content: '法定调整天数',
            align: 'right',
            minWidth: 140,
        },
        {
            id: 'insideDays',
            content: '内部调整天数',
            align: 'right',
            minWidth: 140,
        },
        {
            id: 'frequency',
            content: '触发频率次数',
            align: 'right',
            minWidth: 140,
        },
    ];
    private tableDataResult: any[] = []; // 静态结果表数据
    private hasSelectedData: any[] = []; // 静态结果勾选数据

    ColumnUtil = new ColumnUtil();
    private staticResultQueryDialogVO: DialogVO = new DialogVO(); // 查询请求弹框

    // 信达默认导出顺序
    FSCINDAExportColumn: any[] = [
        { id: 'resultId', content: '序号' },
        { id: 'triggerType', content: '触险类型' },
        { id: 'tradeDate', content: '估值日期' },
        { id: 'prohibitionDate', content: '连续违规天数' },
        { id: 'triggerDay', content: '连续预警天数' },
        { id: 'dictFundCodes', content: '产品代码(名称)' },
        { id: 'entryCode', content: '条目编号' },
        { id: 'entryName', content: '风险说明' },
        { id: 'result', content: '计算结果(单位)' },
        { id: 'thresholdValue', content: '条目触发值' },
        { id: 'dictStockCodes', content: '证券代码(名称)' },
        { id: 'branchValues', content: '分支值' },
        { id: 'numerator', content: '分子值' },
        { id: 'denominator', content: '分母值' },
        { id: 'investBalance', content: '可投余量' },
        { id: 'legalDays', content: '法定调整天数' },
        { id: 'insideDays', content: '内部调整天数' },
        { id: 'frequency', content: '触发频率次数' },
        { id: 'controlGrade', content: '风险等级' },
        { id: 'resultInformation', content: '结果信息' },
        { id: 'calculateDate', content: '计算日期' },
    ];

    async mounted() {
        await this.getShowErrorType();
        this.historyColumns.forEach(ele => {
            if (ele.id == 'errorMessage') {
                ele.show = this.showErrorType;
            }
        });
        this.historyColumns = this.historyColumns.filter((item: any) => item.show !== false);
        this.columns = this.ColumnUtil.handleColumns(this.columns, 'id', 'resultId', this.historyColumns, true);
        this.showFieldList = this.columns;
        // await this.queryLayout();
        this.pageQuery(1);
    }

    // 查询静态是否展示错误类型
    async getShowErrorType() {
        let values = getSystem() || [];
        if (!getSystem().length) {
            await new Promise((resolve, reject) => {
                this.$axios
                    .get('/systemParam/list')
                    .then((res: any) => {
                        values = res;
                        resolve(res);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        }
        let param;
        // 静态结果页面是否查询错误类型，1-开启，0-关闭
        param = values.find(item => item.paramKey == 'STATIC_REPORT_IS_ERROR_TYPE')?.paramValue;
        if (!param) {
            this.showErrorType = false;
            return;
        }
        if (param == '0') {
            this.showErrorType = false;
        } else if (param == '1') {
            this.showErrorType = true;
        }
    }

    // 结果分页
    private pageQuery(currentPage?: number): void {
        const url = this.activeValue === 'sumFirst' ? '/static/fscinda/result/list/sum' : '/static/fscinda/history/result/list/sum';
        this.tableDataResultLoading = true;
        currentPage && (this.page.currentPage = currentPage);
        this.$axios
            .post(url, {
                ...this.staticResultReqVO,
                paging: {
                    currentPage: this.page.currentPage,
                    pageSize: this.page.pageSize,
                },
            })
            .then((res: any) => {
                if (this.showErrorType) {
                    this.tableDataResult = res.list;
                } else {
                    this.tableDataResult = res.list.filter(item => item.triggerType != '4');
                }
                this.page.total = res.total;
                this.tableDataResultLoading = false;
                this.fieldKey++;
            })
            .catch(() => {
                this.tableDataResultLoading = false;
            });
    }

    /**
     * 表头排序(静态结果)
     */
    handleSort(column: any) {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        const sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        let sort = '';
        const property = column.property;
        if (sortType) {
            if (property == 'entryCode') {
                if (sortType == 'DESC') {
                    sort = "DECODE(INSTR(C_ENTRY_CODE,'YH'),1,1,0) DESC,TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) DESC";
                } else {
                    sort = "DECODE(INSTR(C_ENTRY_CODE,'YH'),1,1,0) DESC,TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) ASC";
                }
            } else if (property === 'calculateDate') {
                if (sortType == 'DESC') {
                    sort = 'D_CAL_DATE DESC, D_CAL_TIME DESC';
                } else {
                    sort = 'D_CAL_DATE ASC, D_CAL_TIME ASC';
                }
            } else {
                sort = this.sortParamObj[property] + ' ' + sortType;
            }
        }
        this.staticResultReqVO.sort = sort;
        this.pageQuery(1);
    }

    // 导出
    private loadout(): void {
        if (this.hasSelectedData.length < 1 || !this.hasSelectedData) {
             this.$message.warning('请先勾选导出的数据');
             return;
        }
        let data = this.hasSelectedData;
        // 信达默认导出顺序
            this.$confirm('是否下载文件?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
            }).then(() => {
                if (this.activeValue === 'sumFirst') {
                    const url = '/static/fscinda/result/sum/export';
                 //   this.staticResultReqVO.exportKeys = XEUtils.map(data, item => item.resultId);
                    this.staticResultReqVO.reFundCode = XEUtils.map(data, item => item.fundCode);
                    this.staticResultReqVO.entryCodes = XEUtils.map(data, item => item.entryCode);
                    downLoadFile({
                        url: url,
                        method: 'post',
                        data: { ...this.staticResultReqVO },
                    });
                } else {
                   // this.staticResultReqVO.exportKeys = XEUtils.map(data, item => item.resultId);
                    this.staticResultReqVO.reFundCode = XEUtils.map(data, item => item.fundCode);
                    this.staticResultReqVO.entryCodes = XEUtils.map(data, item => item.entryCode);
                    this.$axios.post('/static/fscinda/history/result/sum/export', { ...this.staticResultReqVO }).then((res: any) => {
                        this.$emit('updateActiveTab', 'third');
                    });
                }
            });
    }

    // 结果刷新
    private refreshStatic(): void {
        this.hasSelectedData = [];
        this.pageQuery(1);
    }

    // 查询
    private queryStatic(): void {
        const title = this.activeValue == 'sumFirst' ? '静态汇总结果高级查询' : '静态历史汇总结果高级查询';
        this.staticResultQueryDialogVO = this.staticResultQueryDialogVO.getAddDialog(title);
    }

    // 高级查询返回值
    private staticResultQueryReturn(val): void {
        this.staticResultReqVO = val;
        this.pageQuery(1);
    }

    // 详情
    private handleRowOperateSumLook(row): void {
        const isHistory = this.activeValue === 'sumSecond';
        this.$emit('handleRowOperateSumLook', { row, isHistory });
    }

    // 走势图
    private handleRowOperateChart(row): void {
        this.$emit('handleRowOperateChart', row);
    }

    // 全选
    private selectAllValueEvent({ selection }): void {
        this.hasSelectedData = selection;
    }

    // 部分勾选
    private selectValueChangeEvent({ selection }): void {
        this.hasSelectedData = selection;
    }

    /* **************************** 布局设置start ***************************** */
    showFieldList: any[] = []; // 要显示的表格列
    selectedFieldList: any[] = []; // 已选择字段列表
    fixedFieldList: any[] = []; // 固定字段列表
    tableDataResultNumKey: number = 1; // 静态结果Key
    fieldKey: number = 1;
    // 获取页面布局信息
    async queryLayout() {
        let url = 'RISK_RES';
        let columns = this.columns;

        if (this.activeValue == 'sumSecond') {
            url = 'RISK_RESULT_H';
            columns = this.historyColumns;
        }
        const resList: any = await new Promise((resolve, reject) => {
            getTableLayout(url)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        console.log(resList, 'resList');
        if (resList) {
            let list: any;
            console.log(list, 'list');

            try {
                list = JSON.parse(resList);
            } catch (err) {
                list = resList;
            }
            this.selectedFieldList = [];
            list.forEach(ele => {
                const obj = columns.find(item => item.id == ele.id);
                obj && this.selectedFieldList.push(obj);
            });
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        } else {
            this.showFieldList = columns;
            this.selectedFieldList = columns;
        }
        console.log(this.showFieldList, 'showFieldList');
        this.tableDataResultNumKey++;
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    /* **************************** 布局设置END ***************************** */

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    getAlign(ele: any) {
        let obj = this.columns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'left';
    }

    // 格式化产品代码
    private formatDictFundCodes(cellValue): string {
        let valueStr = XEUtils.map(cellValue, item => {
            if (item) {
                return item.dictKey + '(' + item.dictKeyName + ')';
            } else {
                return '--';
            }
        });
        return valueStr.toString();
    }

    formatAssetCodes(cellValue) {
        let retData = [];
        cellValue &&
            cellValue.map(key => {
                let name = (this.assetList.find(item => item.assetCode == key) || {}).assetName;
                retData.push(`${key}(${name})`);
            });
        return retData.toString() || '--';
    }

    formatFdAcCodes(cellValue) {
        let retData = [];
        cellValue &&
            cellValue.map(key => {
                let name = (this.fdAcList.find(item => item.fundAccountCode == key) || {}).fundAccountName;
                retData.push(`${key}(${name})`);
            });
        return retData.toString() || '--';
    }
}
</script>
<style lang="scss" scoped>
// tabs主内容
.container {
    padding: 10px 20px;
    .header {
        padding: 10px;
        border: 1px solid #ccc;
    }
    .dataInfo {
        margin-top: 10px;
        border: 1px solid #ccc;
    }
}
</style>
<style lang="scss">
.tips-popper {
    max-width: 700px;
    max-height: 300px;
    overflow: auto;
}
</style>
